import axios from 'axios'
import { Loading, Message } from 'element-ui'
import { router } from '@/router/index.js'
import qs from 'qs'

let loading

const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '正在加载中...',
    background: 'rgba(0.0.0.7)'
  })
}

const endLoading = () => {
  loading.close()
}

const service = axios.create({
  baseURL: 'http://localhost:5001',
  timeout: 50000,
  headers: { 'Content-Type': 'application/json' },
  paramsSerializer: {
    serialize (params) {
      return qs.stringify(params, { allowDots: true })
    }
  }
})

// 请求拦截
service.interceptors.request.use(config => {
  // 开始加载动画
  startLoading()
  // 判断localStorage中是否有token
  if (localStorage.getItem('node-token')) {
    // 设置同意的请求头 请求header
    config.headers.Authorization = localStorage.getItem('node-token')
  }
  return config
}, err => {
  return Promise.reject(err)
})

// 响应拦截
service.interceptors.response.use(response => {
  // 结束加载动画
  endLoading()
  if (response.status !== 200) {
    return this.$message.error('网络请求发生错误')
  }
  if (response.status === 401 || response.data.code === 401) {
    // 清除localStorage
    localStorage.clear()
    return router.push('/login')
  }
  return response.data
}, err => {
  // 错误提醒
  endLoading()
  // 响应码401，token失效
  // 获取错误状态码
  const { status } = err.response
  if (status === 401) {
    Message.error('token失效，请重新登录')
    // 清除token
    localStorage.clear()
    return router.push('/login')
  }
  Message.error(err.message)
  return Promise.reject(err)
})

export default service
